import re

from fastapi import APIRouter, Form, HTTPException, Depends
from sqlalchemy.orm import Session

from schemas import UserRegister, UserLogin
from db import get_db
from datetime import datetime, timedelta
from jose import jwt
from auth import User, get_current_active_user
from auth import SECRET_KEY, pwd_context


router = APIRouter(prefix="/api/user", tags=["用户"])


@router.post("/login")
def login(form: UserLogin, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.phone == form.phone).first()
    if not user:
        raise HTTPException(status_code=401, detail="用户不存在")
    if not pwd_context.verify(form.password, user.password):
        raise HTTPException(status_code=401, detail="密码错误")
    expiration = datetime.utcnow() + timedelta(minutes=60 * 24 * 15)
    token = jwt.encode({"user_id": user.id, "exp": expiration}, SECRET_KEY, algorithm="HS256")
    return {"token": token, "code": 200}


@router.post("/register")
async def register_user(form: UserRegister, db: Session = Depends(get_db)):
    phone = re.sub(r'\D', '', form.phone)
    if not re.match(r'^1[3-9]\d{9}$', phone):
        raise HTTPException(status_code=400, detail="手机号格式错误")
    if form.password!= form.password_confirm:
        raise HTTPException(status_code=400, detail="两次密码不一致")
    db_user = db.query(User).filter(User.phone == phone).first()
    if db_user:
        db.close()
        raise HTTPException(status_code=400, detail="用户已存在")
    hashed_password = pwd_context.hash(form.password)
    if len(form.password) < 8:
        raise HTTPException(status_code=400, detail="密码长度至少为8位")
    new_user = User(name=form.name, phone=phone, password=hashed_password)
    db.add(new_user)
    db.commit()
    db.close()
    return {"message": "注册成功"}